import pytz
from django import forms
from django.http import JsonResponse
from rest_framework.response import Response
from rest_framework.views import APIView
from app01.models import Site, SubCategory
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage


class SiteForm(forms.ModelForm):
    class Meta:
        model = Site
        # fields = '__all__'
        fields = ['url', 'name', 'is_show', 'username', 'password', 'category']

class UrlSite_api(APIView):
    def get(self, request):
        page = request.query_params.get('page', 1)
        pagesize = request.query_params.get('pagesize', 100)
        url = request.query_params.get("url", None)
        category = request.query_params.get("category", None)

        subid = SubCategory.objects.filter(id=category).first()
        dic = {}
        if url:
            dic['url__icontains'] = url
        if category:
            dic['category_id'] = subid

        datas = Site.objects.filter(**dic).order_by('-sort')    # 查询对象集
        paginator = Paginator(datas, int(pagesize))
        if page is not None:
            sites = paginator.get_page(int(page))
        # except PageNotAnInteger:
        #     sites = paginator.get_page(1)  # 如果请求的页码不是整数，返回第一页
        # except EmptyPage:
        #     sites = paginator.get_page(paginator.num_pages)  # 如果请求的页码不存在，返回最后一页
        data = []
        for item in sites:
            data.append({
                'CreatedTime': item.CreatedTime.strftime("%Y-%m-%d %H:%M:%S"),
                'UpdatedTime': item.UpdatedTime.strftime("%Y-%m-%d %H:%M:%S"),
                'id': item.id,
                'name': item.name,
                'url': item.url,
                'logo_url': item.logo_url,
                'describtion': item.describtion,
                'is_show': item.is_show,
                'username': item.username,
                'password': item.password,
                'category': item.category.name,
            })
        data = {
            "code": 200,
            "msg": "查询成功",
            'total': paginator.count,
            "data": data
        }
        return JsonResponse(data)


    def post(self, request):
        form = SiteForm(request.data)
        if form.is_valid():
            form.save()
            data = {'code': 200, "msg": "新增成功", 'data': ""}
        else:
            data = {'code': 503, "msg": "新增失败", 'data': form.errors}
        return JsonResponse(data)

# class Site_Api(MSGView):
#     def get(self, request, module, *args, **kwargs):
#         if module == 'all':
#             return self.get_all(request)
#         if module == 'list':
#             return self.get_list(request)
#         else:
#             return super().warn('请求地址不存在')
#
#     def post(self, request, module, *args, **kwargs):
#         if module == 'add':
#             return self.add_info(request)
#         elif module == 'edit':
#             return self.edit_info(request)
#         elif module == 'delete':
#             return self.delete(request)
#         else:
#             return super().warn('请求地址不存在')